package com.cheyun.netsalev3.utils

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.graphics.drawable.Drawable
import android.net.Uri
import android.telephony.PhoneNumberUtils
import android.view.Gravity
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import com.cheyun.netsalev3.MyApplication
import com.cheyunkeji.er.utils.TimeUtils
import java.util.*
import java.util.regex.Pattern


/**
 * 工具类
 */

object FunctionUtils {
    /**
     * 将px值转换为dip或dp值，保证尺寸大小不变
     */
    @JvmStatic
    fun px2dip(context: Context, pxValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (pxValue / scale + 0.5f).toInt()
    }

    /**
     * 将dip或dp值转换为px值，保证尺寸大小不变
     *
     */
    @JvmStatic
    fun dip2px(context: Context, dipValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (dipValue * scale + 0.5f).toInt()
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     */
    fun px2sp(context: Context, pxValue: Float): Int {
        val fontScale = context.resources.displayMetrics.scaledDensity
        return (pxValue / fontScale + 0.5f).toInt()
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     */
    fun sp2px(context: Context, spValue: Float): Int {
        val fontScale = context.resources.displayMetrics.scaledDensity
        return (spValue * fontScale + 0.5f).toInt()
    }


    /**
     * 字符串添加&emsp变成固定长度
     */
    fun stringLeng(s: String, leng: Int? = 5): String {
        var temlenght = s.length - leng!!
        when (temlenght > 0) {
            true -> return s.substring(0, leng)
            else -> {
                var temstring = ""
                for (i in 1..Math.abs(temlenght)) {
                    temstring += "&ensp;"
                }
                return s + temstring
            }
        }
    }

    /**
     * 代码设置DrawableLeft
     */
    fun myDrawableLeft(view: TextView, drawableid: Int) {
        var drawable = MyApplication.getInstance().getDrawable(drawableid)
        setIntrinsicBounds(drawable)
        val drawables = view.compoundDrawables
        view.setCompoundDrawables(drawable, drawables[1], drawables[2], drawables[3])
    }

    private fun setIntrinsicBounds(drawable: Drawable?) {
        drawable?.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
    }


    /**
     * 日历星期转换
     */
    fun calendarWeek(i: Int): String {
        return when (i) {
            1 -> "日"
            2 -> "一"
            3 -> "二"
            4 -> "三"
            5 -> "四"
            6 -> "五"
            7 -> "六"
            else -> ""
        }
    }

    /**
     * 拨打电话（跳转到拨号界面，用户手动点击拨打）
     *
     * @param phoneNum 电话号码
     */
    fun callPhone(content: Context, phoneNum: String) {
        val intent = Intent(Intent.ACTION_DIAL)
        val data = Uri.parse("tel:$phoneNum")
        intent.data = data
        content.startActivity(intent)
    }

    /**
     * 发送短信
     * @param phoneNumber
     * @param message
     */
    fun sendSMSTo(content: Context, phoneNumber: String, message: String) {
        if (PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber)) {
            val intent = Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:$phoneNumber"))
            intent.putExtra("sms_body", message)
            content.startActivity(intent)
        }
    }

    /**
     * 获取当前时间
     */
    fun getTime(): String {
        val c = Calendar.getInstance()
        val year = c.get(Calendar.YEAR)
        val month = c.get(Calendar.MONTH) + 1
        val day = c.get(Calendar.DAY_OF_MONTH)
        val hour = c.get(Calendar.HOUR_OF_DAY)
        val minute = c.get(Calendar.MINUTE)

        var s = formatTime(year.toString(), month.toString(), day.toString(), hour, minute)
        return s
    }

    fun getTime3(): String {
        val c = Calendar.getInstance()
        val year = c.get(Calendar.YEAR)
        val month = c.get(Calendar.MONTH) + 1
        val day = c.get(Calendar.DAY_OF_MONTH)
        val hour = c.get(Calendar.HOUR_OF_DAY)
        val minute = c.get(Calendar.MINUTE)
        val second = c.get(Calendar.SECOND)
        var s = formatTime(year.toString(), month.toString(), day.toString(), hour, minute,second)
        return s
    }

    fun startAppWithPackageName(context: Context, packageName: String) {
        //根据包名获取启动首页的intent 这个intent有可能为空
        val intent = context.packageManager.getLaunchIntentForPackage(packageName)
        if (intent != null) {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(intent)
        }
    }

    /**
     * 获取当前时间
     */
    fun getTime2(): String {
        val c = Calendar.getInstance()
        val year = c.get(Calendar.YEAR)
        val month = c.get(Calendar.MONTH) + 1
        val day = c.get(Calendar.DAY_OF_MONTH)
        var s = year.toString() + "-" +
                String.format(Locale.getDefault(), "%02d", month.toInt()) + "-" +
                String.format(Locale.getDefault(), "%02d", day.toInt())
        return s
    }

    /**
     * 验证手机号码,座机号
     */
    fun isPhone(phone: String, context: Context): Boolean {
        var tel = "^(0[0-9]{2,3}(\\-)?)?([1-9][0-9]{6,7})$"
        val regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$"
        val p = Pattern.compile(regex)
        val t = Pattern.compile(tel)
        if(!((phone.length == 11 && p.matcher(phone).matches())||(phone.length<16&&t.matcher(phone).matches()))){
            Toast.makeText(context, "请填入正确的电话号码", Toast.LENGTH_LONG).show()
            return false;
        }else{
            return true
        }

//        return if (phone.length != 11) {
//            Toast.makeText(context, "手机号应为11位数", Toast.LENGTH_LONG).show()
//            false
//        } else {
//            val p = Pattern.compile(regex)
//            val m = p.matcher(phone)
//            val isMatch = m.matches()
//            if (!isMatch) {
//                Toast.makeText(context, "请填入正确的电话号码", Toast.LENGTH_LONG).show()
//            }
//            isMatch
//        }
    }

    /**
     * 验证手机号码,座机号不提示
     */
    fun isPhone2(phone: String, context: Context): Boolean {
        var tel = "^(0[0-9]{2,3}(\\-)?)?([1-9][0-9]{6,7})$"
//        val regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$"
        val regex = "^1(3|4|5|6|7|8|9)\\d{9}$"
        val p = Pattern.compile(regex)
        val t = Pattern.compile(tel)
        if(!((phone.length == 11 && p.matcher(phone).matches())||(phone.length<16&&t.matcher(phone).matches()))){
            return false;
        }else{
            return true
        }
    }

    fun isPhone3(phone: String): Boolean {
//        val regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$"
        val regex = "^1(3|4|5|6|7|8|9)\\d{9}$"
        val p = Pattern.compile(regex)
        if(!((phone.length == 11 && p.matcher(phone).matches()))){
            return false;
        }else{
            return true
        }
    }

    /**
     * 格式化播放时间
     * @param seconds 秒数
     * 时间＜1小时显示分秒，显示样式 00:20
     * 时间 ≥1小时显示时分秒，显示样式 01:11:12*
     */
    fun formatSeconds(seconds: Long): String {
        val standardTime: String
        if (seconds <= 0) {
            standardTime = "00:00"
        } else if (seconds < 60) {
            standardTime = String.format(Locale.getDefault(), "00:%02d", seconds % 60)
        } else if (seconds < 3600) {
            standardTime = String.format(Locale.getDefault(), "%02d:%02d", seconds / 60, seconds % 60)
        } else {
            standardTime = String.format(Locale.getDefault(), "%02d:%02d:%02d", seconds / 3600, seconds % 3600 / 60, seconds % 60)
        }
        return standardTime
    }

    /**
     * 格式化年月日 时间
     */
    fun formatTime(year: String, month: String, day: String, hourOfDay: Int, minute: Int): String {
        var s = ""
        try {
            s = year.toString() + "-" +
                    String.format(Locale.getDefault(), "%02d", month.toInt()) + "-" +
                    String.format(Locale.getDefault(), "%02d", day.toInt()) + " "+
                    String.format(Locale.getDefault(), "%02d", hourOfDay) + ":" +
                    String.format(Locale.getDefault(), "%02d", minute)
        } catch (e: Exception) {

        }

        return s
    }

    /**
     * 格式化年月日 时间
     */
    fun formatTime(year: String, month: String, day: String, hourOfDay: Int, minute: Int,second:Int): String {
        var s = ""
        try {
            s = year.toString() + "-" +
                    String.format(Locale.getDefault(), "%02d", month.toInt()) + "-" +
                    String.format(Locale.getDefault(), "%02d", day.toInt()) + " "+
                    String.format(Locale.getDefault(), "%02d", hourOfDay) + ":" +
                    String.format(Locale.getDefault(), "%02d", minute)+ ":" +
                    String.format(Locale.getDefault(), "%02d", second)
        } catch (e: Exception) {

        }

        return s
    }

    /**
     * 格式化年月日 时间
     */
    fun formatTime(year: String, month: String, day: String): String {
        var s = ""
        try {
            s = year.toString() + "-" +
                    String.format(Locale.getDefault(), "%02d", month.toInt()) + "-" +
                    String.format(Locale.getDefault(), "%02d", day.toInt())
        } catch (e: Exception) {

        }

        return s
    }

    fun getCurrentVersion(context: Context):String{
        var versionName: String = ""
        try {
            val pm = context.getPackageManager()
            val pi = pm.getPackageInfo(context.packageName, 0)
            versionName = pi.versionName
            if (versionName == null || versionName.length <= 0) {
                return ""
            }
        }catch (e:Exception){

        }
        return versionName
    }

    fun getCurrentCode(context: Context): String {
        var versionCode: String = ""
        try {
            val pm = context.getPackageManager()
            val pi = pm.getPackageInfo(context.packageName, 0)
            versionCode = pi.versionCode.toString()
        } catch (e: Exception) {

        }
        return versionCode
    }

    fun setAlertDialogPos(dialog: Dialog){
        var window = dialog.window
        if (dialog != null && window != null) {
            var attr = window.getAttributes()
            if (attr != null) {
                attr.height = ViewGroup.LayoutParams.WRAP_CONTENT
                attr.width = (AppCongfig.width  * 0.95).toInt()
                attr.gravity = Gravity.CENTER

                window.attributes = attr
            }
        }
    }

    fun getMessageTime(dateline:String):String{
        var tm = "";
        var time = CommonFunc.compareDate(CommonFunc.getDateFormat(dateline,1), Date())
        if (time < 60) {
            tm = "刚刚"
        } else if (time >= 60 && time < 3600) {
            tm = (time / 60).toString() + "分钟前"
        } else if (time >= 3600 && time < 3600 * 24) {
            tm = (time / 3600).toString() + "小时前"
        } else if (time >= 3600 * 24 && time < 3600 * 24 * 30) {
            tm = (time / (3600 * 24)).toString() + "天前"
        } else {
            tm = (time / (3600 * 24 * 30)).toString() + "个月前"
//            tm = CommonFunc.getDateFormat(dateline,1)
        }
        return tm
    }


}